<?php

declare(strict_types=1);

namespace app\traits;

//use app\model\Files;
use app\MyException;
use think\Exception;
use think\facade\Filesystem;
use think\facade\Request;
use think\response\Json;

trait UploadTrait
{
    /**
     * 通用文件上传处理方法
     * @param string $key 上传的文件字段名
     * @param string $destination 存储路径
     * @return Json
     */
    private function handleUpload(string $key, string $destination): Json
    {
        try {
            $files = Request::file($key);
            if (empty($files)) {
                \exception('请上传文件！');
            }
            // 从配置文件中获取上传的规则
            $uploadConfig = getConfigs('upload_config');

            $rules = '';
            $upload_max_index = array_search($key.'_upload_max', array_column($uploadConfig, 'sign'));
            if ($upload_max_index !== false) {
                $rules .= "fileSize:{$uploadConfig[$upload_max_index]['value']}";
            }
            $upload_ext_index = array_search($key.'_ext', array_column($uploadConfig, 'sign'));
            if ($upload_ext_index !== false) {
                $rules .= !empty($rules) ? "|fileExt:{$uploadConfig[$upload_ext_index]['value']}" : "fileExt:{$uploadConfig[$upload_ext_index]['value']}";
            }
            $upload_mime_index = array_search($key.'_mime', array_column($uploadConfig, 'sign'));
            if ($upload_mime_index !== false) {
                $rules .= !empty($rules) ? "|fileMime:{$uploadConfig[$upload_mime_index]['value']}" : "fileMime:{$uploadConfig[$upload_mime_index]['value']}";
            }

            validate([$key=>$rules])->check([$key=>$files]);
            $driver_index = array_search('upload_mode', array_column($uploadConfig, 'sign'));
            $driver = $uploadConfig[$driver_index]['value'];

            $storage_directory_index = array_search('upload_storage_directory', array_column($uploadConfig, 'sign'));
            $storage_directory =$uploadConfig[$storage_directory_index]['value'];
            $path = $storage_directory.'/'.$destination;
            $saveName = \yzh52521\filesystem\facade\Filesystem::disk($driver)->putFile($path, $files);
            $saveName = str_replace('\\','/',$saveName);
            if($driver == 'local'){
                $url = getConfigs('upload_config.local_domain').'/storage/'.$saveName;
            }else{
                $url      = \yzh52521\filesystem\facade\Filesystem::disk($driver)->url( $saveName );
            }
            return success(['path'=>$url]);
        }catch (\Exception $e){
            return error($e->getMessage());
        }
    }

    /**
     * 上传图片
     */
    public function upimg()
    {
        return $this->handleUpload('image', 'images');
    }

    /**
     * 上传视频
     */
    public function upvideo()
    {
        return $this->handleUpload('video', 'videos');
    }

    /**
     * 上传文件
     */
    public function upfile()
    {
        return $this->handleUpload('file', 'files');
    }
}
